﻿var designClass = "design_class", hideClass = "hide_class", browseClass = "browse_class", addClass = "add_class", editClass = "edit_class";
var upWindow = window.parent.frames["zwIframe"];
if (!upWindow) {
    upWindow = window.parent.frames["componentDiv"].frames["zwIframe"];
}
function fy_dialog_close() {
//	window.parent.$(".mask").remove();
//	window.parent.parent.$(".layui-layer-iframe").parent().find(".layui-layer-close").trigger("click");
    window.parent.$(".layui-layer-iframe").parent().find(".layui-layer-close").trigger("click");
}

function getUpFields(name) {
    return upWindow.$("[validate*='name:\"" + name + "\"']");
}
function getUpFieldsByFieldval(name) {
    return upWindow.$("[fieldval*='displayName:\"" + name + "\"']");
}
function addOrDelRepeat(name, newLength) {
    var upFields = getUpFieldsByFieldval(name);
    var uplength = upFields.length;
    if (uplength != newLength) {
        var tbody = upFields.eq(0).parent();
        while (!tbody.is("tbody")) {
            tbody = tbody.parent();
        }
        for (var i = 0, count = Math.abs(newLength - uplength); i < count; i++) {
            if (newLength > uplength) {
                upWindow.fy_addEmpty(tbody.children().last());
            } else {
                upWindow.fy_delCurrentRepeat(tbody.children().last());
            }
        }
    }
}
function getUpAccountFieldValue(name) {
    var field = getUpFields(name).eq(0);
    return {
        displayValue: field.is("span") ? field.text() : field.val(),
        value: eval("(" + field.parent("span").attr("fieldVal") + ")").value
    };
}

function getUpFieldValue(field) {
    var fieldVal = field.attr("fieldVal");
    var editTag = field.hasClass(editClass);
    var browseTag = field.hasClass(browseClass);
    var addTag = field.hasClass(addClass);
    if (fieldVal != null && typeof (fieldVal) != 'undefined') {
        fieldVal = eval("(" + fieldVal + ")");
    } else {
        return null;
    }
    var obj = new Object();
    obj.displayName = fieldVal.displayName;
    obj.name = fieldVal.name;
    var tag = true;
    switch (fieldVal.inputType) {
        case "text":
        case "textarea":
            if (editTag) {
                obj.value = field.find("#" + fieldVal.name).val();
            } else if (browseTag) {
                obj.value = fieldVal.value;
            } else if (addTag) {
                obj.value = field.find("#" + fieldVal.name).val();
            }
            break;
        case "checkbox":
            if (editTag) {
                obj.value = field.find("#" + fieldVal.name).val();
            } else if (browseTag) {
                obj.value = field.find("#" + fieldVal.name).val();
            }
            break;
        case "radio":
            if (editTag) {
                obj.value = field.find(":radio:checked").attr("val4cal");
            } else if (browseTag) {
                obj.value = field.find(":radio:checked").attr("val4cal");
            }
            break;
        case "select":
            if (editTag) {
                obj.value = field.find("#" + fieldVal.name + " option:selected")
                    .attr("val4cal");
            } else if (browseTag) {
                obj.value = field.find("#" + fieldVal.name).attr("val4cal");
            }
            break;
        case "date":
            if (editTag) {
                obj.value = field.find("#" + fieldVal.name).val();
                if (obj.value != "") {
                    obj.value = obj.value + " 00:00";
                }
            } else if (browseTag) {
                obj.value = fieldVal.value;
            }
            break;
        case "datetime":
            if (editTag) {
                obj.value = field.find("#" + fieldVal.name).val();
            } else if (browseTag) {
                obj.value = fieldVal.value;
            }
            break;
        case "flowdealoption":
            if (editTag) {
                obj.value = fieldVal.value;
            } else if (browseTag) {
                obj.value = fieldVal.value;
            } else if (addTag) {
                obj.value = fieldVal.value;
            }
            break;
        case "lable":
            if (editTag) {
                obj.value = fieldVal.value;
            } else if (browseTag) {
                obj.value = fieldVal.value;
            }
            break;
        case "relationform":
            if (editTag) {
                obj.value = fieldVal.value;
            } else if (browseTag) {
                obj.value = fieldVal.value;
            }
            break;
        case "relation":
            if (editTag || browseTag) {
                obj.value = fieldVal.value;
            }
            break;
        case "project":
            if (editTag) {
                obj.value = field.find("#" + fieldVal.name).val();
            } else if (browseTag) {
                obj.value = fieldVal.value;
            }
            break;
        case "member":
        case "multimember":
        case "account":
        case "multiaccount":
        case "department":
        case "multidepartment":
        case "post":
        case "multipost":
        case "level":
        case "multilevel":
            if (editTag) {
                obj.value = field.find("#" + fieldVal.name + "_txt").val();
            } else if (browseTag) {
                obj.value = field.find("#" + fieldVal.name).text();
            }
            break;
        case "attachment":
        case "image":
        case "document":
            if (editTag || browseTag) {
                var attNames = "";
                var tempField = field.find("#" + fieldVal.name);
                var tempFileId = "";
                if (tempField[0].tagName.toLowerCase() == "input") {
                    tempFileId = tempField.val();
                } else if (tempField[0].tagName.toLowerCase() == "span") {
                    tempFileId = tempField[0].innerHTML;
                }
                var atts = upWindow.getAttBySubreference(tempFileId);
                for (var j = 0; j < atts.length; j++) {
                    attNames += atts[j].filename + ",";
                }
                if (attNames != "") {
                    attNames = attNames.substr(0, attNames.length - 1);
                }
                obj.value = attNames;
            }
            break;
        case "outwrite":
            if (editTag || browseTag) {
                obj.value = fieldVal.value;
            }
            break;
        case "externalwrite-ahead":
            if (editTag || browseTag) {
                obj.value = fieldVal.value;
            }
            break;
        case "exchangetask":
            if (editTag || browseTag) {
                obj.value = fieldVal.value;
            }
            break;
        case "querytask":
            if (editTag || browseTag) {
                obj.value = fieldVal.value;
            }
            break;
        default:
            tag = false;
    }
    if (obj.value != undefined) {
        obj.value = obj.value.replace("\r\n", ";");
        obj.value = obj.value.replace("\n", ";");
    }
    return obj;
}
function setUpFieldValue(name, value) {
    upWindow.$("[fieldval*='displayName:\"" + name + "\"']").find("input").val(
        value);
    upWindow.$("[fieldval*='displayName:\"" + name + "\"']").find("input")
        .trigger("blur");
}

function setUpFieldValue2(field, value, displayValue, index) {


    var fieldVal = field.attr("fieldVal");
    var editTag = field.hasClass(editClass);
    var addTag = field.hasClass(addClass);
    value = trim(value);
    displayValue = trim(displayValue);
    if (fieldVal != null && typeof (fieldVal) != 'undefined') {
        fieldVal = eval("(" + fieldVal + ")");
    } else {
        return null;
    }

    // var obj = new Object();
    // obj.displayName = fieldVal.displayName;
    // obj.name = fieldVal.name;
    var tag = true;
    switch (fieldVal.inputType) {
        case "text":
        case "textarea":
            if (editTag) {
                var inField = field.find("#" + fieldVal.name);
                console.info("value : "+value+"fieldVal.name = "+fieldVal.name)
                console.log(inField)
                inField.val(value);
                // inField.attr("readonly", true);
                console.info("editTag---->>")
                inField.trigger("blur");
            } else if (addTag) {
                var inField = field.find("#" + fieldVal.name);
                inField.val(value);
                // inField.attr("readonly", true);
                console.info("addTag---->>")
                inField.trigger("blur");
            }
            break;
        case "checkbox":
            if (editTag) {
                field.find("#" + fieldVal.name).attr("checked", true);
                field.find("#" + fieldVal.name).trigger("click");
            }
            break;
        case "radio":
            if (editTag) {
                field.find(":radio").eq(index).attr("checked", true);
                field.find(":radio").eq(index).trigger("click");
            }
            break;
        case "select":
            if (editTag) {
                // if (value) {
                // field.find("#" + fieldVal.name).value(value);
                // } else {
                var options = field.find("#" + fieldVal.name + " option");
                for (var k = 0; k < options.length; k++) {
                    if (options.eq(k).text() == value)
                        options.eq(k).attr("selected", true);
                }
                // }
                field.find("#" + fieldVal.name).trigger("change");
            }
            break;
        case "date":
            if (editTag) {
                field.find("#" + fieldVal.name).val(value);
                field.find("#" + fieldVal.name).trigger("blur");
            }
            break;
        case "datetime":
            if (editTag) {
                field.find("#" + fieldVal.name).val(value);
                field.find("#" + fieldVal.name).trigger("blur");
            }
            break;
        case "member":
        case "multimember":
        case "account":
        case "multiaccount":
        case "department":
        case "multidepartment":
        case "post":
        case "multipost":
        case "level":
        case "multilevel":
            if (editTag) {
                alert(editTag);
                field.find("#" + fieldVal.name + "_txt").val(value);
            }
            break;
    }
}

/**
 * 去除左右空格
 */
function trim(str) {
    return (str) ? (typeof str == "string" ? str.replace(/^\s*/, "").replace(
        /\s*$/, "") : str) : "";
}

Array.prototype.indexOf = function (value) {
    for (var i = 0, l = this.length; i < l; i++)
        if (this[i] == value)
            return i;
    return -1;
};

// ////////////////////树////////////////////////////
/**
 * 合格供应商
 */
var qualifiedSuppliersTree = null;// 合格供应商
/**
 * 潜在供应商
 */
var potentialSuppliersTree = null;// 潜在供应商

/**
 * 生成合格供应商供货范围树状图
 */
function createQualifiedSuppliersTree() {
    qualifiedSuppliersTree = new dhtmlXTreeObject("qualifiedSuppliersTreeDIV",
        "100%", "100%", 0);
    qualifiedSuppliersTree.setSkin("csh_dhx_skyblue");
    qualifiedSuppliersTree
        .setImagePath("./oa2uap/js/tree/imgs/csh_dhx_skyblue/");
    qualifiedSuppliersTree.enableCheckBoxes(1);
    qualifiedSuppliersTree.enableThreeStateCheckboxes(true);
    // qualifiedSuppliersTree.loadXMLString(typeXML);
}
/**
 * 生成潜在供应商供货范围树状图
 */
function createPotentialSuppliersTree() {
    potentialSuppliersTree = new dhtmlXTreeObject("potentialSuppliersTreeDIV",
        "100%", "100%", 0);
    potentialSuppliersTree.setSkin("csh_dhx_skyblue");
    potentialSuppliersTree
        .setImagePath("./oa2uap/js/tree/imgs/csh_dhx_skyblue/");
    potentialSuppliersTree.enableCheckBoxes(1);
    potentialSuppliersTree.enableThreeStateCheckboxes(true);
}

/**
 * 设置Tree的checkbox disabled
 */
function setTreeAllCheckBoxDisabled() {
    qualifiedSuppliersTree.deleteChildItems('0');
    potentialSuppliersTree.deleteChildItems('0');
}

function setAllowCheckNodes(qualifiedSupplyRange, potentialSupplyRange) {

    qualifiedSuppliersTree.deleteChildItems('0');
    potentialSuppliersTree.deleteChildItems('0');
    qualifiedSuppliersTree.loadXMLString(qualifiedSupplyRange);
    potentialSuppliersTree.loadXMLString(potentialSupplyRange);

    for (var i in qualifiedSupplyRange) {
        qualifiedSuppliersTree.disableCheckbox(qualifiedSupplyRange[i], 0);
    }

    for (var i in potentialSupplyRange) {
        potentialSuppliersTree.disableCheckbox(potentialSupplyRange[i], 0);
    }
}
/**
 *
 * @param code
 *            供应商编码
 * @param queryType
 *            查询类型 1:仅查询供应商名称 2: 查询供应商名称和供应商基本信息
 * @param operator
 *            处理方法
 */
function _ajax(url, operator) {
    document.getElementById("lodingDiv").style.display = '';
    var xmlhttp = null;
    if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera,
        xmlhttp = new XMLHttpRequest();
    } else {// code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == 4) {
            if (xmlhttp.status == 200) {
                text = xmlhttp.responseText;
                if (text == 2) {
                    alert("用户还未登陆，或者已掉线");
                } else if (text == 3) {
                    alert("供应商编码不能为空。");
                } else {
                    operator(text);
                }
            } else {
                alert("连接服务器异常");
            }
            document.getElementById("lodingDiv").style.display = 'none';
        }
    };
    xmlhttp.open("get", url + "&temp=" + Math.random(), true);
    xmlhttp.send();
}

function queryProviderInfo(isInit) {
    var code = document.getElementById("query_providerCode").value;

    if (!code || code == "") {
        if (!isInit) {
            alert("需要查询的供应商编码不能为空");
        }
        return;
    }

    document.getElementById("providerName").value = "";
    document.getElementById("providerCode").value = "";
    setTreeAllCheckBoxDisabled();

    _ajax(
        "./oa2uapController.do?method=getProviderInfoAndRangeXMLByCode&code="
        + code,
        function (text) {
            if (text == 1) {
                alert("无法获取对应的制造部ＩＤ");
            } else {
                var result = eval("(" + text + ")");

                if (result.state) {
                    if (result.state == 1) {
                        alert("不存在供应商编码：" + code);
                    } else if (result.state == 2) {
                        alert("该供应商在当前制造部无供货范围");
                    } else if (result.state == 3) {
                        document.getElementById("providerName").value = result.companyName[0];
                        document.getElementById("providerCode").value = code;
                        setAllowCheckNodes(result.qualifiedSupplyRange,
                            result.potentialSupplyRange);

                        if (isInit) {
                            var inputs = getUpFieldsByFieldval("供货范围PK");
                            var supplierStateInputs = getUpFieldsByFieldval("潜在或合格");
                            for (var i = 0; i < inputs.length; i++) {
                                var state = getUpFieldValue(supplierStateInputs
                                    .eq(i)).value;
                                if (state == '合格') {
                                    qualifiedSuppliersTree.setCheck(
                                        inputs[i].value, true);
                                } else if (state == '潜在') {
                                    potentialSuppliersTree.setCheck(
                                        inputs[i].value, true);
                                }
                            }
                        }
                    } else {
                        alert("数据异常，请重试");
                    }
                } else {
                    alert("获取数据异常");
                }
            }
        });
}

function getTRParentNode(node) {
    var tempNode = node;
    while (true) {
        if (tempNode && tempNode.tagName.toUpperCase() != "TR") {
            tempNode = tempNode.parentNode;
        } else {
            break;
        }
    }
    return tempNode.parentNode;
}

function onButtonClick() {

    if (getUpFieldsByFieldval("供货范围1_填写").length > 0) {
        setUpFieldValue2(getUpFieldsByFieldval("供应商编码1").eq(0), document
            .getElementById("providerCode").value);

        setUpFieldValue2(getUpFieldsByFieldval("供应商名称1").eq(0), document
            .getElementById("providerName").value);
    } else {
        setUpFieldValue2(getUpFieldsByFieldval("供应商编码").eq(0), document
            .getElementById("providerCode").value);

        setUpFieldValue2(getUpFieldsByFieldval("供应商名称").eq(0), document
            .getElementById("providerName").value);
    }
    // 合格
    var qualifiedSuppliersArray = qualifiedSuppliersTree.getAllChecked() == "" ? []
        : qualifiedSuppliersTree.getAllChecked().split(',');
    // 潜在
    var potentialSuppliersArray = potentialSuppliersTree.getAllChecked() == "" ? []
        : potentialSuppliersTree.getAllChecked().split(',');

    var num = qualifiedSuppliersArray.length + potentialSuppliersArray.length;

    addOrDelRepeat("供货范围1", num);

    var qualifiedSuppliersArrayLength = qualifiedSuppliersArray.length;

    for (var i = 0; i < qualifiedSuppliersArrayLength; i++) {
        writeToForm(qualifiedSuppliersTree, qualifiedSuppliersArray[i], '合格', i);
    }

    for (var i = 0; i < potentialSuppliersArray.length; i++) {
        writeToForm(potentialSuppliersTree, potentialSuppliersArray[i], '潜在', i
            + qualifiedSuppliersArrayLength);
    }
    fy_dialog_close();
}

function writeToForm(tree, rangeID, type, index) {
    console.info("rangeID = "+rangeID)
    if (rangeID == '0' && rangeID.replace(' ', '') == '') {
        return;
    }
    if (getUpFieldsByFieldval("供货范围1_填写").length > 0) {

        var pRangeID = tree.getParentId(rangeID);
        if (pRangeID == '0') {
            setUpFieldValue2(getUpFieldsByFieldval("供货范围1_填写").eq(index), tree
                .getItemText(rangeID));
            setUpFieldValue2(getUpFieldsByFieldval("供货范围2_填写").eq(index), "");
            setUpFieldValue2(getUpFieldsByFieldval("供货范围3_填写").eq(index), "");
        } else {
            var ppRangeID = tree.getParentId(pRangeID);
            if (ppRangeID == '0') {
                setUpFieldValue2(getUpFieldsByFieldval("供货范围1_填写").eq(index), tree
                    .getItemText(pRangeID));
                setUpFieldValue2(getUpFieldsByFieldval("供货范围2_填写").eq(index), tree
                    .getItemText(rangeID));
                setUpFieldValue2(getUpFieldsByFieldval("供货范围3_填写").eq(index), "");

            } else {
                setUpFieldValue2(getUpFieldsByFieldval("供货范围1_填写").eq(index), tree
                    .getItemText(ppRangeID));
                setUpFieldValue2(getUpFieldsByFieldval("供货范围2_填写").eq(index), tree
                    .getItemText(pRangeID));
                setUpFieldValue2(getUpFieldsByFieldval("供货范围3_填写").eq(index), tree
                    .getItemText(rangeID));

            }
        }
        setUpFieldValue2(getUpFieldsByFieldval("潜在或合格_填写").eq(index), type);
        setUpFieldValue2(getUpFieldsByFieldval("供货范围PK").eq(index), rangeID);
    } else {
        var pRangeID = tree.getParentId(rangeID);
        if (pRangeID == '0') {
            setUpFieldValue2(getUpFieldsByFieldval("供货范围1").eq(index), tree
                .getItemText(rangeID));
            setUpFieldValue2(getUpFieldsByFieldval("供货范围2").eq(index), "");
            setUpFieldValue2(getUpFieldsByFieldval("供货范围3").eq(index), "");
        } else {
            var ppRangeID = tree.getParentId(pRangeID);
            if (ppRangeID == '0') {
                setUpFieldValue2(getUpFieldsByFieldval("供货范围1").eq(index), tree
                    .getItemText(pRangeID));
                setUpFieldValue2(getUpFieldsByFieldval("供货范围2").eq(index), tree
                    .getItemText(rangeID));
                setUpFieldValue2(getUpFieldsByFieldval("供货范围3").eq(index), "");

            } else {
                setUpFieldValue2(getUpFieldsByFieldval("供货范围1").eq(index), tree
                    .getItemText(ppRangeID));
                setUpFieldValue2(getUpFieldsByFieldval("供货范围2").eq(index), tree
                    .getItemText(pRangeID));
                setUpFieldValue2(getUpFieldsByFieldval("供货范围3").eq(index), tree
                    .getItemText(rangeID));

            }
        }
        setUpFieldValue2(getUpFieldsByFieldval("潜在或合格").eq(index), type);
        setUpFieldValue2(getUpFieldsByFieldval("供货范围PK").eq(index), rangeID);
    }
}

window.onload = function () {
    createQualifiedSuppliersTree();
    createPotentialSuppliersTree();
    document.getElementById("query_providerCode").value = getUpFieldValue(getUpFieldsByFieldval(
        "供应商编码").eq(0)).value;
    queryProviderInfo(true);
};
